<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">报警记录
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist>
        瓦斯涌出报警
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true" showFooter>
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>基本信息</span></p>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="瓦斯涌出名称" prop="gasMissionName">
                    <el-input v-model="state.formData.gasMissionName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="瓦斯涌出编号" prop="gasMissionCode">
                    <el-select clearable filterable v-model="state.formData.gasMissionCode" placeholder="请选择"
                      @change="gasMissionCodeChange">
                      <el-option v-for="item in state.gasMissionCodeList" :key="item.pointId" :label="item.pointId"
                        :value="item.pointId">
                        <span>{{ item.pointId+'-'+item.placeName }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="安装位置" prop="gasMissionPlace">
                    <el-input disabled v-model="state.formData.gasMissionPlace" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="风速测点编号" prop="windPointCode">
                    <el-select clearable filterable v-model="state.formData.windPointCode" placeholder="请选择"
                      @change="windPointCodeChange">
                      <el-option v-for="item in state.windPointCodeList" :key="item.pointId" :label="item.pointId"
                        :value="item.pointId">
                        <span>{{ item.pointId+'-'+item.placeName }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="安装位置" prop="windPointPlace">
                    <el-input disabled v-model="state.formData.windPointPlace" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>监测地点截面积</span></p>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="系数" prop="factor">
                    <el-input v-model="state.formData.factor" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="宽(米)" prop="width">
                    <el-input v-model="state.formData.width" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="高(米)" prop="height">
                    <el-input v-model="state.formData.height" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>预报设置</span></p>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预报警" prop="predicatedValue">
                    <el-input v-model="state.formData.predicatedValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="持续时间" prop="durationTime">
                    <el-select clearable filterable v-model="state.formData.durationTime" placeholder="请选择">
                      <el-option v-for="item in state.stationOutNumList" :key="item" :label="item+'分钟'" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>详细备注</span></p>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="" prop="remark">
                    <el-input v-model="state.formData.remark" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 报警记录 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>报警记录信息</span>
        </h4>
      </template>
      <template #default>
        <recordInfo :recordInfoList="state.recordInfoList" @querybjjlClick="querybjjlClick"
         :bjjlObj="state.bjjlObj"
          :bjjlThead="state.bjjlObj.bjjlThead" @getPointDatapagebjjl="getPointDatapagebjjl"
          @getPointDatabjjl="getPointDatabjjl"></recordInfo>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import recordInfo from "./alarmInfo/recordInfo";
  import {
    computed,
    reactive
  } from "vue";
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    getlistSitesList,
    getlistPointsBySensorName
  } from '@/api/config'
  import dayjs from 'dayjs'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  components: {
    list_controller
  }
  const upload = ref(null)
  let state = reactive({
    fileList: [],
    drawerShow: false,
    dialogVisiblepictureCardPreview: false,
    dialogImageUrl: '',
    options: {
      tableheads: computed(() => table_headers.configGasOverflow),
      queryList: {
        dropdownUrl: '',
        querys: [],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/gas/overflow/list',
      delUrl: '/gas/overflow/del',
      addUrl: '/gas/overflow/add',
      descUrl: '/gas/overflow/getById',
      editUrl: '/gas/overflow/modify',
    },
    // 表单
    addModal: false,
    modalTitle: '新增瓦斯涌出报警',
    formRef: null,
    formData: {},
    rules: {
      gasMissionName: [{
        required: true,
        message: '请输入瓦斯涌出名称',
        trigger: 'blur'
      }],
      gasMissionCode: [{
        required: true,
        message: '请选择瓦斯涌出编号',
        trigger: 'change'
      }],
      gasMissionPlace: [{
        required: true,
        message: '请输入安装位置',
        trigger: 'blur'
      }],
      windPointCode: [{
        required: true,
        message: '请选择风速测点编号',
        trigger: 'change'
      }],
      windPointPlace: [{
        required: true,
        message: '请输入安装位置',
        trigger: 'blur'
      }],
      factor: [{
        required: true,
        message: '请输入系数',
        trigger: 'blur'
      }],
      width: [{
        required: true,
        message: '请输入宽(米)',
        trigger: 'blur'
      }],
      height: [{
        required: true,
        message: '请输入高(米)',
        trigger: 'blur'
      }],
      predicatedValue: [{
        required: true,
        message: '请输入预报警',
        trigger: 'blur'
      }],
      durationTime: [{
        required: true,
        message: '请输入延迟时间(s)',
        trigger: 'change'
      }]
    },
    editId: undefined,
    gasMissionCodeList: [],
    stationmodelList: [],
    stationInNumList: [],
    forecastTypeList: [
      '上限报警值', '下限报警值', '上下限报警值'
    ],
    stationOutNumList: [0, 0.5, 1, 3, 5, 10, 15, 20, 30],
    bjjlObj: {
      bjjlThead: [{
        field: 'startTime',
        title: '报警时间'
      }, {
        field: 'predicatedValue',
        title: '预报值'
      }, {
        field: 'endTime',
        title: '结束时间'
      }, {
        field: 'accumulationTime',
        title: '恒值持续时长'
      }, {
        field: 'expressions',
        title: '表达式'
      }],
      listTable: [],
      total: 0,
      alarmCount: undefined,
      accumulationTime: undefined
    },
    recordInfoList: [{
        col: 12,
        type: 'input',
        label: '瓦斯涌出名称',
        field: 'gasMissionName',
        binddata: undefined
      },
      {
        col: 12,
        type: 'input',
        label: '瓦斯涌出测点',
        field: 'gasMissionCode',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '风速测点',
        field: 'windPointCode',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '报警次数',
        field: 'predicateNum',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '累计报警时间',
        field: 'totalAccumulationTime',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '监测地点 系数',
        field: 'factor',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '监测地点 宽(米)',
        field: 'width',
        binddata: undefined
      },
      {
        col: 8,
        type: 'input',
        label: '监测地点 高(米)',
        field: 'height',
        binddata: undefined
      }
    ]
  })
  // 查看按钮
  function lookBtn(row) {
    state.drawerShow = true
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.recordInfoList.forEach(item => {
          item.binddata = res.data[item.field]
        })
      }
    })
  }

  function querybjjlClick(data) {
    let obj = {
      endTime: dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss.000'),
      startTime:dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss.000'),
      gasOverflowNameList: [state.formData.gasMissionName],
      pageNum: 1,
      pageSize: 10
    }
    state.bjjlObj.obj = obj
    // 历史预报警列表
    axios.post("/hisGasOverflow/gasOverflowStatics", state.bjjlObj.obj).then(res => {
      if (res.data.list != null) {
        state.recordInfoList[3].binddata = res.data.list[0].predicateNum
        state.recordInfoList[4].binddata = res.data.list[0].totalAccumulationTime
      }
    })
    getlistPointDetailPrealarm()
  }

  function getlistPointDetailPrealarm(obj) {
    axios.post("/hisGasOverflow/gasOverflowDetail", state.bjjlObj.obj).then(res => {
      if (res.data.list != null) {
        state.bjjlObj.listTable = res.data.list
        state.bjjlObj.total=res.data.total
      } else {
        state.bjjlObj.listTable = []
      }
    })
  }

  function getPointDatapagebjjl(val) {
    state.bjjlObj.obj.pageNum = val
    getlistPointDetailPrealarm()
  }

  function getPointDatabjjl(val) {
    state.bjjlObj.obj.pageNum = 1
    state.bjjlObj.obj.pageSize = val
    getlistPointDetailPrealarm()
  }

  // 新增按钮
  async function addBtn(row) {
    state.modalTitle = '新增瓦斯涌出报警'
    state.addModal = true
    state.formData = {}
    state.editId = undefined
    state.fileList = []
    await getlistPointsBySensorName({
      sensorName: "瓦斯",
      condition: "A%"
    }).then(res => {
      state.gasMissionCodeList = res.data
    })
    await getlistPointsBySensorName({
      sensorName: "风速",
      condition: "A%"
    }).then(res => {
      state.windPointCodeList = res.data
    })
  }
  // 编辑按钮
  async function editBtn(row) {
    state.modalTitle = '编辑瓦斯涌出报警'
    state.addModal = true
    await getlistPointsBySensorName({
      sensorName: "瓦斯",
      condition: "A%"
    }).then(res => {
      state.gasMissionCodeList = res.data
    })
    await getlistPointsBySensorName({
      sensorName: "风速",
      condition: "A%"
    }).then(res => {
      state.windPointCodeList = res.data
    })
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        state.editId = res.data.id
      }
    })
  }

  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgSuccess('请先勾选所要删除数据!');
      }
    }
   if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if (state.editId) {
          state.formData.id = state.editId
          axios.post(state.options.editUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        } else {
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        }
      }
    })
  }

  function cancel() {
    state.addModal = false
  }

  function getsubstationmodelList() {
    getlistSitesList().then(res => {
      state.stationmodelList = Object.keys(res.data).map(item => {
        return {
          label: res.data[item],
          value: item
        }
      })
    })

  }


  function gasMissionCodeChange(val) {
    state.gasMissionCodeList.forEach(item => {
      if (item.pointId == val) {
        state.formData.gasMissionPlace = item.placeName
      }
    })
  }

  function windPointCodeChange(val) {
    console.log(val, "state.formData.windPointPlace");
    if (val) {
      state.windPointCodeList.forEach(item => {
        if (item.pointId == val) {
          state.formData.windPointPlace = item.placeName
        }
      })
    } else {
      state.formData.windPointPlace = undefined
    }
  }

  function pointModelChange(val) {
    state.stationInNumList.forEach(item => {
      if (val == item.code) {
        state.formData.place = item.place
      }
    })
  }
  getsubstationmodelList()
</script>
<style lang="scss" scoped>
  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>